package ink.onei.shopping.service.impl;

import ink.onei.common.utils.StringUtils;
import ink.onei.shopping.domain.Detail;
import ink.onei.shopping.domain.Goods;
import ink.onei.shopping.mapper.GoodsMapper;
import ink.onei.shopping.service.IGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 商品Service业务层处理
 * 
 * @author nekotako
 * @date 2024-02-05
 */
@Service
public class GoodsServiceImpl implements IGoodsService  {
    @Autowired
    private GoodsMapper goodsMapper;

    /**
     * 查询商品
     * 
     * @param goodsId 商品主键
     * @return 商品
     */
    @Override
    public Goods selectGoodsById(Long goodsId) {
        return goodsMapper.selectGoodsById(goodsId);
    }

    /**
     * 查询商品列表
     * 
     * @param goods 商品
     * @return 商品
     */
    @Override
    public List<Goods> selectGoodsList(Goods goods) {
        return goodsMapper.selectGoodsList(goods);
    }

    /**
     * 新增商品
     * 
     * @param goods 商品
     * @return 结果
     */
    @Transactional
    @Override
    public int insertGoods(Goods goods) {
        goodsMapper.deleteDetailByGoodsId(goods.getGoodsId());
        insertDetail(goods);
        return goodsMapper.insertGoods(goods);
    }

    /**
     * 修改商品
     * 
     * @param goods 商品
     * @return 结果
     */
    @Transactional
    @Override
    public int updateGoods(Goods goods) {
        goodsMapper.deleteDetailByGoodsId(goods.getGoodsId());
        insertDetail(goods);
        return goodsMapper.updateGoods(goods);
    }

    /**
     * 批量删除商品
     * 
     * @param goodsIds 需要删除的商品主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteGoodsByIds(Long[] goodsIds) {
        goodsMapper.deleteDetailByGoodsIds(goodsIds);
        return goodsMapper.deleteGoodsByIds(goodsIds);
    }

    /**
     * 删除商品信息
     * 
     * @param goodsId 商品主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteGoodsById(Long goodsId) {
        goodsMapper.deleteDetailByGoodsId(goodsId);
        return goodsMapper.deleteGoodsById(goodsId);
    }

    /**
     * 新增商品规格信息
     *
     * @param goods 商品对象
     */
    public void insertDetail(Goods goods) {
        List<Detail> detailList = goods.getDetailList();
        Long goodsId = goods.getGoodsId();
        if (StringUtils.isNotNull(detailList)) {
            List<Detail> list = new ArrayList<>();
            for (Detail detail : detailList) {
                detail.setGoodsId(goodsId);
                list.add(detail);
            }
            if (!list.isEmpty()) {
                goodsMapper.batchDetail(list);
            }
        }
    }
}
